/**
 * 更新用户状态业务逻辑 create by zhuchentong
 * 
 * @2017-04-21
 */
var d1 = require('deviceone')
var storage = require('util/storage')
var constant = require('config/constant')
var server = require('config/server')
var net = require('util/net')
var process = require('lib/process')
var log = require('util/log')
var app = d1.sm('do_App')
/**
 * 获取用户登录状态 0: 未登录 1: 已登出 2: 已登出 3: 已登录 用户id-1 用户token-2
 */
module.exports.getState = function() {
	var userToken = storage.getItem(constant.user.token)
	var userId = storage.getItem(constant.user.id)
	var userState = (userToken ? 2 : 0) + (userId ? 1 : 0)

	switch (userState) {
	case 3:
		userState = constant.user.state.login
		break;
	case 2:
	case 1:
		userState = constant.user.state.logout
		break;
	case 0:
	default:
		userState = constant.user.state.none
		break;
	}

	return userState
}

/**
 * 登录用户通过token
 */
module.exports.loginByToken = function() {
	var process = new promise.Promise()
	var userToken = storage.getItem(constant.user.token)
	net.send({
		server : server.organization.loginByToken,
		data : {
			token : userToken
		},
		success : function(data) {
			module.exports.updateUserData({
				token : userToken,
				user : data
			})
			process.done()
		},
		error : function(data) {
			log.info(data)
			process.done()
		}
	}, true)
	return process
}

/**
 * 更新用户数据
 */
module.exports.updateUserData = function(data) {
	storage.setItem(constant.user.id, data.user.userId)
	storage.setItem(constant.user.token, data.token)
	storage.setItem(constant.user.data, data.user)
}

/**
 * 更新用户数据
 */
module.exports.logout = function() {
	module.exports.clearUserData()
	try {
		app.closePageToID("","","app/login");
	} catch (ex) {
		app.openPage({
			source : "source://view/app/login.ui",
			id : "app/login"
		});
	}
}

/**
 * 更新用户数据
 */
module.exports.clearUserData = function() {
	storage.clearItem(constant.user.id)
	storage.clearItem(constant.user.token)
	storage.clearItem(constant.user.data)
}

// 添加用户属性
Object.defineProperties(module.exports, {
	id : {
		get : function() {
			return storage.getItem(constant.user.id)
		}
	},
	token : {
		get : function() {
			return storage.getItem(constant.user.token)
		}
	},
	data : {
		get : function() {
			return storage.getItem(constant.user.data)
		}
	}
})